package web.commons;

import org.apache.wicket.PageParameters;
import org.apache.wicket.markup.repeater.data.DataView;
import org.apache.wicket.markup.repeater.data.IDataProvider;

//StatelessDataView<Photo> dv;
//add(dv = new StatelessDataView<Photo>("pics", getPhotoProvider(), amount, pageParams) {
//                        private static final long serialVersionUID = 1L;
//                        @Override
//                        protected void populateItem(final Item<Photo> arg0) {
//              }
//});
//
//// call back page class, page paramaters passed, the dataview and 12 pagination links.
//add(new StatelessSimplePagingNavigator("nav", PhotosPage.class, pageParams, dataView, 12));


public abstract class StatelessDataView<T> extends DataView<T> {
    private static final long serialVersionUID = 1L;
    private PageParameters pp;
    private int currentPage;
    private boolean refreshToFirst = false;

    @Override
    protected boolean getStatelessHint() {
        return true;
    }

    protected int getCurrentPageNumber() {
        return currentPage;
    }

    protected void configureCallback(final int pageNumber) {
    }

    @Override
    protected void onBeforeRender() {
        super.onBeforeRender();
        if (refreshToFirst) {
            setRedirect(true);
            PageParameters pp2 = new PageParameters(pp);
            pp2.put(getId(), "0");
            setResponsePage(getWebPage().getClass(), pp2);
        } else {
            configureCallback(getCurrentPageNumber());
        }
    }

    protected int getPageNumber(final String param) {
        String numResult = param;
        if (numResult.contains(".wicket-")) {
            numResult = numResult.substring(0, numResult.indexOf(".wicket-"));
        }
        if (numResult.contains(".")) {
            numResult = numResult.substring(0, numResult.indexOf("."));
        }
        return Integer.valueOf(numResult);
    }

    public StatelessDataView(final String id, final IDataProvider dataProvider, final PageParameters pp) {
        this(id, dataProvider, 14, pp);
    }

    public StatelessDataView(final String id, final IDataProvider dataProvider, final int itemsPerPage,
                             final PageParameters pp) {
        super(id, dataProvider, itemsPerPage);
        this.pp = pp;
        if (pp.getString(id) != null) {
            int pageNum = getPageNumber(pp.getString(id));
            if (pageNum >= 0 && pageNum <= getPageCount()) {
                currentPage = pageNum;
                setCurrentPage(pageNum);
            } else {
                refreshToFirst = true;
            }
        }
    }

}